package com.kindsoft.demo.ad;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;

/**
 * Created by zhoujm on 2020/2/20/020.
 */
@RestController
@RequestMapping("ad")
public class AdTestController {

    private final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    PersonRepository personRepository;

    @GetMapping("create")
    public void add(){
        Person person = new Person("aiaadmin");
        person.setMemberOf(Arrays.asList("CN=Enterprise Admins,CN=Users,DC=unicademo,DC=com"));
        person.setName("aiaadmin");
        person.setPrincipalName("aiaadmin@unicacom.com");
        personRepository.create(person);
    }

    @GetMapping("delete")
    public void delete(String name){
        Person person = new Person();
        person.setName(name);
        personRepository.deletePerson(person);
    }

    @GetMapping("/")
    public String index(){
        SecurityContext securityContext = SecurityContextHolder.getContext();
        UserDetails userDetails = (UserDetails) securityContext.getAuthentication().getPrincipal();
        log.info("userDetails: " + userDetails);
        Person person = personRepository.findByPrincipalName(userDetails.getUsername());
        log.info("person: " + person);
        return "index";
    }

    @GetMapping("test")
    public String test(){
        SecurityContext securityContext = SecurityContextHolder.getContext();
        UserDetails userDetails = (UserDetails) securityContext.getAuthentication().getPrincipal();
        return userDetails.toString();
    }
}
